﻿/**
 *       Project: ServerLib
 *     Copyright: Copyright (C) 2008, Rob Kennedy
 *   Create Date: 2008-07-14 10:16 PM
 * Modified Date: 2008-07-14 10:16 PM    RK  Added comments
 *      Comments: Ignore SA1633.
 *      
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace ServerLib.Data
{
    using Core;

    /// --------------------------------------------------------------------
    /// Project	 : ServerLib
    /// Class	 : ConnectionStringBuilder
    /// Inherits : None.
    /// --------------------------------------------------------------------
    /// <summary>
    /// Builds a database connection string from individual property values
    /// </summary>
    /// <authorname>Rob Kennedy</authorname>
    /// <remarks></remarks>
    /// --------------------------------------------------------------------
    public class ConnectionStringBuilder
    {
        #region Private Properties
        
        /// <summary>Stores the connection string parameter delimiter character</summary>
        private static char parameterDelimiter = ';';

        /// <summary>Stores the connection string parameter value delimiter character</summary>
        private static char paramValueDelimiter = '=';

        /// <summary>Stores the database parameter name</summary>
        private static string databaseParameterName = "Database";

        /// <summary>Stores the user id parameter name</summary>
        private static string userIdParameterName = "User ID";

        /// <summary>Stores the password parameter name</summary>
        private static string userPasswordParameterName = "Password";

        /// <summary>Stores the security connection parameter name</summary>
        private static string userSecureConnectParameterName = "Integrated Security";

        /// <summary>Stores all parameters in a name value pair collection</summary>
        private static NameValuePairCollection parameters = new NameValuePairCollection();
        
        #endregion

        #region Public Properties
        
        /// <summary>
        /// Gets or sets the delimiter character used to delimit parameters in the 
        ///  connection string
        /// </summary>
        public char ParameterDelimiterCharacter
        {
            get 
            { 
                return parameterDelimiter; 
            }
            
            set 
            { 
                parameterDelimiter = value; 
            }
        }
        
        /// <summary>
        ///  Gets or sets the delimiter character used to delimit individual parameter names
        ///  and their value within the connection string.
        /// </summary>
        public char ParameterValueDelimiter
        {
            get 
            { 
                return paramValueDelimiter; 
            }
            
            set 
            { 
                paramValueDelimiter = value; 
            }
        }
        
        /// <summary>
        ///  Gets or sets the parameter name for the default database within the connection string
        /// </summary>
        public string DatabaseParameterName
        {
            get 
            { 
                return databaseParameterName; 
            }
            
            set 
            { 
                databaseParameterName = value; 
            }
        }
        
        /// <summary>
        /// Gets or sets the parameter name for the login user name within the connection string
        /// </summary>
        public string UserIdParameterName
        {
            get 
            { 
                return userIdParameterName; 
            }
            
            set 
            { 
                userIdParameterName = value; 
            }
        }
        
        /// <summary>
        /// Gets or sets the parameter name for the login password within the connection string
        /// </summary>
        public string UserPasswordParameterName
        {
            get 
            { 
                return userPasswordParameterName; 
            }
            
            set 
            { 
                userPasswordParameterName = value; 
            }
        }

        /// <summary>
        /// Gets or sets the parameter name for the login security connection 
        /// type within the connection string
        /// </summary>
        public string UserSecureConnectParameterName
        {
            get 
            { 
                return userSecureConnectParameterName; 
            }
            
            set 
            { 
                userSecureConnectParameterName = value; 
            }
        }

        /// <summary>
        /// Gets or sets the user name within the connection string
        /// </summary>
        public string UserName
        {
            get
            {
                string resultValue = string.Empty;

                if (parameters != null ? parameters.ContainsKey(userIdParameterName) : false)
                {
                    resultValue = parameters[userIdParameterName];
                }

                return resultValue;
            }

            set
            {
                if (parameters != null)
                {
                    if (parameters.ContainsKey(userIdParameterName))
                    {
                        parameters[userIdParameterName] = value;
                    }
                    else
                    {
                        parameters.Add(userIdParameterName, value);
                    }
                }
            }
        }
        
        /// <summary>
        /// Gets or sets the password within the connection string
        /// </summary>
        public string Password
        {
            get
            {
                string resultValue = string.Empty;
                
                if (parameters != null ? parameters.ContainsKey(userPasswordParameterName) : false)
                {
                    resultValue = parameters[userPasswordParameterName];
                }
                
                return resultValue;
            }

            set
            {
                if (parameters != null)
                {
                    if (parameters.ContainsKey(userPasswordParameterName))
                    {
                        parameters[userPasswordParameterName] = value;
                    }
                    else
                    {
                        parameters.Add(userPasswordParameterName, value);
                    }
                }
            }
        }
       
        /// <summary>
        /// Gets or sets the default database within the connection string
        /// </summary>
        public string Database
        {
            get
            {
                string resultValue = string.Empty;
                
                if (parameters != null ? parameters.ContainsKey(databaseParameterName) : false)
                {
                    resultValue = parameters[databaseParameterName];
                }

                return resultValue;
            }

            set
            {
                if (parameters != null)
                {
                    if (parameters.ContainsKey(databaseParameterName))
                    {
                        parameters[databaseParameterName] = value;
                    }
                    else
                    {
                        parameters.Add(databaseParameterName, value);
                    }
                }
            }
        }

        #endregion

        #region Public Constructors

        /// <summary>
        ///  Builds a ConnectionStringBuilder Object
        /// </summary>
        public ConnectionStringBuilder()
            : this(string.Empty)
        {
        }
        
        /// <summary>
        ///  Builds a ConnectionStringBuilder Object
        /// </summary>
        /// <param name="connectionString">The initializing connection string</param>
        public ConnectionStringBuilder(string connectionString)
        {
            this.LoadConnectionStringToParameters(connectionString);
        }
        
        /// <summary>
        ///  Builds a ConnectionStringBuilder Object
        /// </summary>
        /// <param name="connectionString">The initializing connection string</param>
        /// <param name="databaseParamName">The default database parameter name</param>
        /// <param name="userIdParamName">The login user name parameter name</param>
        /// <param name="passwordParamName">The login password parameter name</param>
        /// <param name="secureConnParamName">The security connection type parameter name</param>
        public ConnectionStringBuilder(string connectionString, string databaseParamName, string userIdParamName, string passwordParamName, string secureConnParamName)
        {
            databaseParameterName = databaseParamName;
            userIdParameterName = userIdParamName;
            userPasswordParameterName = passwordParamName;
            userSecureConnectParameterName = secureConnParamName;
            this.LoadConnectionStringToParameters(connectionString);
        }
        
        #endregion

        #region Public Methods

        /// <summary>
        /// Formats a new connection string with a user ID and password.
        /// </summary>  
        /// <param name="connectionStringToFormat">The connection string to format.</param>
        /// <returns>A ConnectionStringBuilder object containing connection string data</returns>
        public static ConnectionStringBuilder CreateNewConnectionString(string connectionStringToFormat)
        {
            return new ConnectionStringBuilder(connectionStringToFormat, databaseParameterName, userIdParameterName, userPasswordParameterName, userSecureConnectParameterName);
        }
        
        /// <summary>
        /// Returns a complete connection string 
        /// </summary>
        /// <returns>The complete database connection string</returns>        
        public override string ToString()
        {
            return this.BuildConnectionString(true);
        }
        
        /// <summary>
        /// Returns a complete connection string
        /// </summary>
        /// <param name="includeCredentialParameters">
        /// If false, does not include login information in the connection string</param>
        /// <returns>A database connection string</returns>
        public string ToString(bool includeCredentialParameters)
        {
            return this.BuildConnectionString(includeCredentialParameters);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Returns a connection string build from class parameter values
        /// </summary>
        /// <param name="dontUseCredentials">If true, builds a connection string without login parameters</param>
        /// <returns>Returns a database connection string value</returns>
        private string BuildConnectionString(bool dontUseCredentials)
        {
            string resultValue = string.Empty;

            for (int idx = 0; idx < parameters.Count; idx++)
            {
                if (dontUseCredentials)
                {
                    if (parameters[idx] == userIdParameterName || parameters.Keys[idx] == userPasswordParameterName || 
                        parameters.Keys[idx] == userSecureConnectParameterName || parameters.Keys[idx] == userSecureConnectParameterName)
                    {
                        resultValue += string.Format("{0}{1}{2}{3}", parameters.Keys[idx], paramValueDelimiter, parameters[idx], parameterDelimiter);
                    }
                }
                else
                {
                    resultValue += string.Format("{0}{1}{2}{3}", parameters.Keys[idx], paramValueDelimiter, parameters[idx], parameterDelimiter);
                }
            }

            return resultValue;
        }

        /// <summary>
        /// Parses a connection string into object property values. 
        /// </summary>
        /// <param name="connectionString">The database connection string to parse</param>
        private void LoadConnectionStringToParameters(string connectionString)
        {
            parameters.Clear();

            string[] parts = connectionString.Split(parameterDelimiter);
            
            if (parts != null ? parts.Length > 0 : false)
            {
                foreach (string part in parts)
                {
                    string[] nvp = part.Split(paramValueDelimiter);
                    
                    if (nvp != null ? nvp.Length == 2 : false)
                    {
                        parameters.Add(nvp[0], nvp[1]);
                    }
                }
            }
        }
        #endregion
    }
}
